<template>
  <!-- 主容器，包含所有内容 -->
  <view class="recommendation-container" :class="{'from-wardrobe': !showFortuneModules}">
    
    <!-- 服装上传须知弹窗 -->
    <ClothesUploadNoticeModal
      :show="showClothesUploadNotice"
      :localKey="clothesUploadLocalKey"
      @update:show="showClothesUploadNotice = $event"
      @agree="handleClothesUploadAgree"
      @disagree="handleClothesUploadDisagree"
    />
    
    <!-- 顶部头部区域（状态栏+导航栏） -->
    <view class="header-area" :class="{'from-wardrobe-header': !showFortuneModules}">
      <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
      <view class="nav-header">
        <!-- 页面标题 -->
        <view class="page-title" style="flex:1;text-align:center;">{{ showFortuneModules ? '时空衣橱（实例演示）' : '智能搭配' }}</view>
        <view class="placeholder-btn"></view>
      </view>
    </view>

    <!-- 内容区域，动态paddingTop适配头部高度 -->
    <view class="content-area" :style="{ paddingTop: headerHeight }">

      <!-- 试穿预览区 -->
      <view class="preview-section">
        <view class="image-comparison">
          <!-- 左侧：上衣/下衣预览 -->
          <view class="left-column">
            <view class="image-placeholder upper" @click="previewImage(selectedTopImage)" :class="{'animating': isTopAnimating}">
              <image v-if="selectedTopImage" :src="selectedTopImage" mode="aspectFit" class="preview-image"></image>
              <text v-else class="placeholder-text">上衣</text>
              <view class="change-btn" @click.stop="openClothesUploadNotice('top')">
                <text>更换</text>
              </view>
            </view>
            <view class="image-placeholder lower" @click="previewImage(selectedBottomImage)" :class="{'animating': isBottomAnimating}">
              <image v-if="selectedBottomImage" :src="selectedBottomImage" mode="aspectFit" class="preview-image"></image>
              <text v-else class="placeholder-text">下衣</text>
              <view class="change-btn" @click.stop="openClothesUploadNotice('bottom')">
                <text>更换</text>
              </view>
            </view>
          </view>
          <!-- 右侧：模特/生成效果图预览 -->
          <view class="right-column" :class="{'zoom-animation': zoomAnimation}">
            <view class="image-placeholder model-area" @click="previewImage(generatedImage || personImage)" :class="{'generating': isGenerating, 'generated': justGenerated, 'animate-model': shouldAnimateModel && modelImageLoaded}">
              <image v-if="generatedImage" :src="generatedImage" mode="aspectFit" class="preview-image" @error="handleImageError('generated')"></image>
              <image v-else :src="personImage" mode="aspectFit" class="preview-image model-image" @load="onModelImageLoad" @error="handleImageError('model')"></image>
              <view class="change-btn" @click.stop="openUploadNoticeModal">
                <text>更换</text>
              </view>
              <!-- AI生成中遮罩 -->
              <view class="generating-overlay" v-if="isGenerating">
                <view class="scanning-line"></view>
                <view class="generating-spinner"></view>
                <text class="generating-text">AI生成中...</text>
                <view class="progress-container">
                  <view class="progress-bar" :style="{ width: progressValue + '%' }"></view>
                </view>
              </view>
              <!-- 生成成功动画 -->
              <view class="success-animation" v-if="showSuccessAnimation">
                <view class="success-circle"></view>
                <view class="success-checkmark"></view>
                <view class="success-ripple"></view>
                <view v-for="(star, index) in 10" :key="'star-'+index" class="success-star" :style="{transform: `rotate(${index * 36}deg) translateX(${50 + index * 5}px)`,animationDelay: `${index * 0.1}s`}" ></view>
                <view class="success-glow"></view>
              </view>
            </view>
          </view>
        </view>
        <!-- 按钮区域：一键试穿和立即体验同一行 -->
        <view class="try-btns-row">
          <button class="try-on-button" @click="callTryOnAPI" :class="{'button-disabled': loading}">
            <view class="button-content">
              <view class="button-icon" v-if="loading">
                <view class="loading-spinner"></view>
              </view>
              <text>一键试穿</text>
            </view>
          </button>
          <button class="try-now-button" @click="goToTryOnDetail">
            <text>立即体验</text>
          </button>
        </view>
      </view>

      <!-- 运势模块 -->
      <view class="fortune-card luck-section">
        <view class="luck-title-container">
          <text class="luck-title">{{ yearFortune.title }}</text>
        </view>
        <view class="liunian-tag-row">
          <text class="liunian-label">流年干支：</text>
          <text class="liunian-value">{{ yearFortune.liuNianText }}</text>
          <text class="liunian-desc">（{{ yearFortune.liuNianDesc }}）</text>
        </view>
        <text class="luck-description">{{ currentLuckText }}</text>
      </view>

      <!-- 运势星级模块（美化卡片） -->
      <view class="fortune-card fortune-star-section">
        <view class="fortune-card-header fortune-star-header">
          <text class="fortune-card-title">{{ overallFortune.title }}</text>
          <view class="fortune-stars">
            <text v-for="i in 5" :key="i" :class="['fortune-star', i <= fortuneStar ? 'active' : '']">★</text>
          </view>
        </view>
        <view class="fortune-star-desc-row">
          <text class="fortune-star-score"><span style="color:#ff5b9a;font-weight:bold;">{{ fortuneStar }}星</span></text>
          <text class="fortune-summary">{{ overallFortune.description }}</text>
        </view>
      </view>

      <!-- 个人幸运色模块（美化卡片） -->
      <view class="fortune-card lucky-color-section">
        <view class="fortune-card-header">
          <text class="fortune-card-title">个人幸运色</text>
        </view>
        <view class="lucky-color-row">
          <view class="lucky-color-group">
            <view class="color-dot main" :style="{background: luckyColorMain.textColor}"></view>
            <text class="color-label">主色：</text>
            <text class="color-value main" style="color:#222">{{ luckyColorMain.name }}</text>
          </view>
          <view class="lucky-color-group">
            <view class="color-dot assist" :style="{background: luckyColorAssist.textColor}"></view>
            <text class="color-label">辅助色：</text>
            <text class="color-value assist" style="color:#222">{{ luckyColorAssist.name }}</text>
          </view>
        </view>
        <text class="color-desc">{{ luckyColorDesc }}</text>
      </view>

      <!-- 2025年运势指数模块（美化卡片） -->
      <view class="fortune-card fortune-index-section">
        <view class="fortune-card-header">
          <text class="fortune-card-title">2025年运势指数</text>
        </view>
        <view class="fortune-index-list">
          <view class="fortune-index-item" v-for="item in fortuneIndexList" :key="item.type">
            <view class="fortune-index-type">{{ item.label }}</view>
            <view class="fortune-index-stars">
              <text v-for="i in 5" :key="i" :class="['fortune-star', i <= item.stars ? 'active' : '']">★</text>
            </view>
            <view class="fortune-index-desc">{{ item.desc }}</view>
          </view>
        </view>
      </view>

      <!-- 建议穿搭标签模块（美化卡片） -->
      <view class="fortune-card wear-tags-section">
        <view class="fortune-card-header">
          <text class="fortune-card-title">建议穿搭标签</text>
        </view>
        <view class="wear-tags-list">
          <view class="wear-tags-row" v-if="wearTags && wearTags.colors && wearTags.colors.length > 0">
            <text class="tag-label">服装颜色</text>
          <view class="tags-group">
              <text v-for="(tag, idx) in wearTags.colors" :key="'color-'+idx" :class="['tag', tag.className]">{{ tag.text }}</text>
          </view>
        </view>
          <view class="wear-tags-row" v-if="wearTags && wearTags.styles && wearTags.styles.length > 0">
            <text class="tag-label">服装风格</text>
          <view class="tags-group">
              <text v-for="(tag, idx) in wearTags.styles" :key="'style-'+idx" :class="['tag', tag.className]">{{ tag.text }}</text>
          </view>
        </view>
          <view class="wear-tags-row" v-if="wearTags && wearTags.types && wearTags.types.length > 0">
            <text class="tag-label">服装类型</text>
            <view class="tags-group">
              <text v-for="(tag, idx) in wearTags.types" :key="'type-'+idx" :class="['tag', tag.className]">{{ tag.text }}</text>
      </view>
          </view>
        </view>
          </view>

      <!-- 新增重点月份提示模块（优化布局，支持后续API数据） -->
      <view class="fortune-card month-tips-section">
        <view class="fortune-card-header">
          <text class="fortune-card-title">重点月份提示</text>
        </view>
        <view class="month-tips-list">
          <view class="month-tip-item" v-for="(item, idx) in monthTipsList" :key="idx">
            <view class="month-dot"></view>
            <text class="month-label">{{ item.month }}：</text>
            <text class="month-tip-content">{{ item.tip }}</text>
          </view>
        </view>
      </view>

      <!-- 推荐商品列表 -->
      <view class="recommendation-list-section">
        <view class="section-header">
          <text class="section-title">搭配单品推荐</text>
          <text class="view-all">查看全部</text>
        </view>
        <view class="recommendation-item" v-for="(item, index) in recommendItems" :key="index">
          <view class="item-image-placeholder">
            <image :src="item.image_url" mode="aspectFit" class="item-image"></image>
          </view>
          <view class="item-details">
            <text class="item-name">{{ item.name }}</text>
            <text class="item-description">{{ item.description }}</text>
            <view class="item-tags">
              <text class="tag recommended" v-if="index === 0">推荐</text>
              <text class="tag hot" v-if="index === 0">热销</text>
              <text class="tag style" v-if="index === 1">合理搭</text>
              <text class="tag new" v-if="index === 1">新品</text>
              <text class="tag luck" v-if="index === 2">开运</text>
              <text class="tag discount" v-if="index === 2">优惠</text>
            </view>
          </view>
          <view class="item-action">
            <text class="item-price">¥{{ item.price || '199' }}</text>
            <button class="add-button" @click="tryOnItem(getItemType(item, index), item.image_url)">一键试穿</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import Cache from '../../utils/cache';
import { LOGIN_STATUS } from '../../config/cache';
import { getUserInfo } from '../../api/user';
import UploadNoticeModal from '@/components/UploadNoticeModal.vue';
import ClothesUploadNoticeModal from '@/components/ClothesUploadNoticeModal.vue';
// 引入穿搭推荐API接口
import { 
  getFashionRecommend, 
  getFashionStatus, 
  submitFashionRating, 
  healthCheck 
} from '../../api/fashion';

export default {
  components: {
    UploadNoticeModal,
    ClothesUploadNoticeModal
  },
  data() {
    return {
      statusBarHeight: 20, // 默认状态栏高度
      navBarHeight: 50, // 导航栏高度
      starCount: 5, // 星星数量
      selectedTopImage: '', // 选中的上衣图片
      selectedBottomImage: '', // 选中的下衣图片
      selectedAccessory: '', // 选中的配饰
      API_BASE_URL: 'https://dashscope.aliyuncs.com/api/v1',
      API_KEY: 'sk-dc4fdd4e5a344a17a0312a9b552b95b8',
      FASHION_API_URL: 'https://jtmjrefalbbp.sealosgzg.site', // 穿搭推荐API的基础URL
      personImage: 'https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1760598171/p812706.png',
      taskId: '', // 保存任务ID
      generatedImage: '', // 生成的图片URL
      loading: false, // 加载状态
      currentDate: '', // 当前日期
      // 动画状态
      isGenerating: false,
      justGenerated: false,
      showSuccessAnimation: false,
      isTopAnimating: false,
      isBottomAnimating: false,
      zoomAnimation: false, // 添加缩放动画状态
      progressValue: 0, // 进度条值
      progressInterval: null, // 进度条定时器
      uploadServerUrl: '/api/upload/image', // 服务器上传接口地址
      imageUrl: '', // 上传后的图片链接
      
      // 接收传入参数
      modelParams: {
        modelImage: '', // 从上一页接收的模特照片URL
        birthDate: '',
        birthTime: '',
        location: '',
        tripDate: '',
        tripTime: '',
        style: '',
        tags: ''
      },
      
      // 控制运势相关模块的显示
      showFortuneModules: true,
      
      // 打字机动画相关
      luckDescription: new Date().getFullYear() + '年，日主辛金（阴金）生于巳月，乙木偏财透干，巳火正官藏支，形成「财官相生」格局。本年易受贵人提携，但火旺克金需注意呼吸道健康。职场有晋升机遇，但需主动争取；感情上易遇条件优越的异性，但需防短暂露水情缘。',
      currentLuckText: '',
      luckTextIndex: 0,
      luckTypingTimer: null,
      
      modelImageLoaded: false, // 模特图片是否已加载
      shouldAnimateModel: true, // 是否应该给模特添加动画
      
      // 试衣记录相关
      recordSaved: false, // 标记是否已保存记录，避免重复保存
      analysisText: '', // 分析文本
      suitableTags: [], // 适合标签
      notSuitableTags: [], // 不适合标签
      
      // 推荐商品列表
      recommendItems: [
        {
          name: "甜美粉色针织衫",
          description: "柔软亲肤面料，提升桃花运势",
          price: "199",
          image_url: "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1389646171/p801338.webp",
          item_type: "top"
        },
        {
          name: "高腰百褶半身裙",
          description: "A字型设计，修饰身形，增添甜美感",
          price: "259",
          image_url: "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1389646171/p801340.jpeg",
          item_type: "bottom"
        },
        {
          name: "温柔气质V领毛衣",
          description: "精选羊绒面料，V领设计优雅显瘦，凸显颈部线条美",
          price: "129",
          image_url: "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1389646171/p801327.jpeg",
          item_type: "top"
        }
      ],
      
      // 添加用户信息字段
      userInfo: {
        token: '',
        avatar: '',
        nickname: '',
        userId: ''
      },
      
      // 穿搭推荐API相关
      fashionRequestId: '', // 穿搭推荐请求ID
      fashionLoading: false, // 穿搭请求加载状态
      fashionData: null, // 穿搭推荐数据
      fashionPollingTimer: null, // 状态轮询定时器
      
      // 穿搭标签数据
      wearTags: {
        colors: [],
        styles: [],
        types: []
      },
      
      // ... 其他数据不变
      fortuneStar: 4, // 初始化综合运势星级
      fortuneIndexList: [
        {
          type: 'peach',
          label: '桃花运',
          stars: 4,
          desc: '夏季易有办公室恋情或邂逅，但长期发展需观察对方诚意。'
        },
        {
          type: 'career',
          label: '事业运',
          stars: 5,
          desc: '乙木偏财助力开职场新局，9-10月可能有关键信项目突破。'
        },
        {
          type: 'health',
          label: '健康运',
          stars: 3,
          desc: '注意颈椎劳损（通勤久坐）和季节性过敏。'
        }
      ],
      luckyColorMain: {
        name: '月光银',
        color: 'linear-gradient(135deg,#e0eafc,#cfdef3)',
        textColor: '#b0b7bd' // 银灰色
      },
      luckyColorAssist: {
        name: '松石绿',
        color: 'linear-gradient(135deg,#a8edea,#fed6e3)',
        textColor: '#26a69a' // 松石绿色
      },
      luckyColorDesc: '增强金行气场，调和火气，助人际和谐',
      monthTipsList: [
        { month: '3月', tip: '避免财务借贷，穿白色增强判断力' },
        { month: '7月', tip: '团队合作佳，绿色系提升贵人运' },
        { month: '11月', tip: '健康波动期，需保证睡眠' }
      ],
      showUploadNotice: false,
      
      // 运势数据相关
      fortuneData: null, // 保存完整的运势数据
      
      // 年度运势
      yearFortune: {
        title: '2025年运势解析',
        liuNianText: '乙己年',
        liuNianDesc: '木火相生',
        description: '暂无年度运势数据'
      },
      
      // 综合运势
      overallFortune: {
        title: '2025年综合运势',
        star: 4,
        description: '事业与财运机遇突出，健康需稍加留意。'
      },
      showClothesUploadNotice: false,
      clothesUploadType: '', // 'top' 或 'bottom'
      uploadNoticeLocalKey: 'hideUploadNoticeModal_home_model',
      clothesUploadLocalKey: 'hideClothesUploadNoticeModal_home_top',
    }
  },
  computed: {
    // 确保返回有效值
    headerHeight() {
      // 使用固定或计算值，避免可能的错误
      const totalHeight = Number(this.statusBarHeight || 20) + Number(this.navBarHeight || 50);
      return totalHeight + 'px';
    },
    
    // 当前引导步骤的样式
    // 删除 guideStyle、currentGuideText、currentGuideArrow
    
    // 当前引导文本
    // 删除 currentGuideText
    
    // 当前引导箭头方向
    // 删除 currentGuideArrow
  },
  onLoad(options) {
    // 获取状态栏高度
    this.getStatusBarHeight();
    
    // 打印用户登录信息，改为从store中获取
    console.log('===== 用户登录信息 =====');
    
    // 检查API URL是否正确
    this.checkApiUrls();
    
    // 直接调用API获取用户信息
    let that = this;
    getUserInfo().then(res => {
      console.log('登录成功，服务器返回的用户信息：', res.data);
      console.log('uid:', res.data.uid);
      console.log('nickname:', res.data.nickname);
      console.log('phone:', res.data.phone);
      
      // 保存到本地存储以便其他页面使用
      uni.setStorageSync('uid', res.data.uid);
      uni.setStorageSync('nickname', res.data.nickname);
      uni.setStorageSync('phone', res.data.phone);
      
      // 测试穿搭推荐API
      console.log('===== 开始测试穿搭推荐API =====');
      
      // 先测试健康检查
      // this.testHealthCheck();
      
      // 3秒后测试异步穿搭推荐
      // setTimeout(() => {
      //   this.testFashionRecommend();
      // }, 3000);
      
    }).catch(err => {
      console.error('获取用户信息失败:', err);
      
      // 即使获取用户信息失败，也测试穿搭推荐API（使用默认/测试值）
      setTimeout(() => {
        this.testHealthCheck();
      }, 1000);
      
      setTimeout(() => {
        this.testFashionRecommend();
      }, 4000);
    });
      
    
    // 初始化文本为空，确保每次进入都有打字效果
    this.currentLuckText = '';
    
    // 解析接收到的参数
    if (options) {
      this.modelParams = {
        modelImage: options.modelImage || '',
        birthDate: options.birthDate || '',
        birthTime: options.birthTime || '',
        location: options.location || '',
        tripDate: options.tripDate || '',
        tripTime: options.tripTime || '',
        style: options.style || '',
        tags: options.tags || ''
      };
      
      console.log('接收到的参数:', this.modelParams);
      
      // 如果有模特图片URL，则设置到personImage
      if (this.modelParams.modelImage) {
        // 确保URL是完整的URL（包含http或https前缀）
        let imageUrl = this.modelParams.modelImage;
        
        // 检查URL是否包含编码字符，尝试解码
        if (imageUrl && imageUrl.includes('%')) {
          try {
            imageUrl = decodeURIComponent(imageUrl);
            console.log('已解码URL:', imageUrl);
          } catch (e) {
            console.error('URL解码失败:', e);
          }
        }
        
        // 确保URL以http开头
        if (imageUrl && imageUrl.indexOf('http') !== 0 && imageUrl.indexOf('//') !== 0) {
          // 尝试使用相对路径或完整路径
          if (getApp().globalData.HTTP_REQUEST_URL) {
            imageUrl = getApp().globalData.HTTP_REQUEST_URL + '/' + imageUrl.replace(/^\/+/, '');
            console.log('已构建完整URL:', imageUrl);
          } else {
            // 如果不是以http或//开头，使用默认图片代替
            console.log('URL格式不正确，使用默认图片');
            imageUrl = 'https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1760598171/p812706.png';
          }
        }
        
        this.personImage = imageUrl;
        console.log('设置模特图片URL:', this.personImage);
        this.shouldAnimateModel = true; // 启用模特动画
      }
      
      
      // 修改动画逻辑，不管从哪里进来都有动画效果
      setTimeout(() => {
        this.zoomAnimation = true;
        
        // 1.5秒后开始打字机动画
        setTimeout(() => {
          this.startTypingAnimations();
          
          // 动画完成后恢复正常大小
          setTimeout(() => {
            this.zoomAnimation = false;
          }, 2500);
        }, 1500);
      }, 500);
    } else {
      // 即使没有参数，也应该执行动画
      setTimeout(() => {
        this.zoomAnimation = true;
        
        // 1.5秒后开始打字机动画
        setTimeout(() => {
          this.startTypingAnimations();
          
          // 动画完成后恢复正常大小
          setTimeout(() => {
            this.zoomAnimation = false;
          }, 2500);
        }, 1500);
      }, 500);
    }
    
    // 默认上衣图片
    const defaultTopImage = 'https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1389646171/p801338.webp';
    // 如果本地缓存没有上衣图片，则设置默认图片并保存
    let cachedTopImage = uni.getStorageSync('home_page_top_image');
    if (!cachedTopImage) {
      this.selectedTopImage = defaultTopImage;
      uni.setStorageSync('home_page_top_image', defaultTopImage);
    } else {
      this.selectedTopImage = cachedTopImage;
    }
    
    // 测试解析运势数据
    setTimeout(() => {
      this.testParseFortuneData();
    }, 1000);
  },
  onReady() {
    // 这个函数留空，移除所有内部调用
  },
  methods: {
    // 获取状态栏高度
    getStatusBarHeight() {
      try {
        const res = uni.getSystemInfoSync();
        // 只获取状态栏高度，避免其他复杂操作
        this.statusBarHeight = res.statusBarHeight || 20;
        console.log('状态栏高度：', this.statusBarHeight);
      } catch (e) {
        console.error('获取系统信息失败', e);
        // 出错时使用默认值
        this.statusBarHeight = 20;
      }
    },
    
    
    // 设置默认的推荐商品数据
    setDefaultRecommendations() {
      console.log('设置默认推荐商品');
      // 保留当前的推荐商品
      if (this.recommendItems && this.recommendItems.length > 0) {
        console.log('已有推荐商品，不进行默认设置');
        return;
      }
      
      // 设置默认的推荐商品
      this.recommendItems = [
        {
          name: "甜美粉色针织衫",
          description: "柔软亲肤面料，提升桃花运势",
          price: "199",
          image_url: "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1389646171/p801338.webp",
          item_type: "top"
        },
        {
          name: "高腰百褶半身裙",
          description: "A字型设计，修饰身形，增添甜美感",
          price: "259",
          image_url: "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1389646171/p801340.jpeg",
          item_type: "bottom"
        },
        {
          name: "温柔气质V领毛衣",
          description: "精选羊绒面料，V领设计优雅显瘦，凸显颈部线条美",
          price: "129",
          image_url: "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1389646171/p801327.jpeg",
          item_type: "top"
        }
      ];
    },
    
   
    // 处理试穿功能
    tryOnItem(type, imageUrl) {
      console.log('试穿商品:', type, imageUrl);
      
      // 检查是否已有生成图片，如果有则提示需要重新生成
      const hasGeneratedImage = this.generatedImage ? true : false;
      
      // 根据类型设置不同部位的图片并添加动画效果
      if (type === 'top') {
        this.isTopAnimating = true;
        this.selectedTopImage = imageUrl;
        setTimeout(() => {
          this.isTopAnimating = false;
        }, 1500); // 延长动画时间
      } else if (type === 'bottom') {
        this.isBottomAnimating = true;
        this.selectedBottomImage = imageUrl;
        setTimeout(() => {
          this.isBottomAnimating = false;
        }, 1500); // 延长动画时间
      } else if (type === 'accessory') {
        this.selectedAccessory = imageUrl;
        // 可以在这里添加配饰的展示逻辑
      }
      
      // 显示成功提示
      uni.showToast({
        title: '已添加到试衣区',
        icon: 'success',
        duration: 1500
      });
      
      // 如果已有效果图，需要清除并提示用户重新生成
      if (hasGeneratedImage) {
        this.generatedImage = ''; // 清除已生成的效果图
        this.showSuccessAnimation = false; // 关闭成功动画
        this.justGenerated = false; // 重置生成状态
        
        // 稍后提示用户需要重新试穿
        setTimeout(() => {
          uni.showToast({
            title: '请重新点击"一键试穿"',
            icon: 'none',
            duration: 2000
          });
        }, 1600);
      }
      
      // 滚动到页面顶部的试衣区
      this.scrollToTop();
    },
    
    // 调用阿里云试衣API
    callTryOnAPI() {
      if (!this.selectedTopImage && !this.selectedBottomImage) {
        uni.showToast({
          title: '请先选择衣服',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      
      if (this.loading) return; // 防止重复点击
      
      this.loading = true;
      
      // 先添加缩放动画效果
      this.zoomAnimation = true;
      this.scrollToTop(); // 滚动到顶部
      
      // 延迟一点启动生成动画，让缩放动画先执行
      setTimeout(() => {
        this.isGenerating = true; // 开始生成动画
        // 启动进度条动画
        this.startProgressAnimation();
        
        console.log('===== 试衣API请求开始 =====');
        console.log('请求参数:');
        console.log('- 上衣图片:', this.selectedTopImage || '无');
        console.log('- 下衣图片:', this.selectedBottomImage || '无');
        console.log('- 模特图片:', this.personImage);
        
        // 构建请求参数
        const requestData = {
          model: "aitryon",
          input: {
            person_image_url: this.personImage
          },
          parameters: {
            resolution: -1,
            restore_face: true
          }
        };
        
        // 添加上衣和下衣参数
        if (this.selectedTopImage) {
          requestData.input.top_garment_url = this.selectedTopImage;
        }
        
        if (this.selectedBottomImage) {
          requestData.input.bottom_garment_url = this.selectedBottomImage;
        }
        
        console.log('完整请求数据:', JSON.stringify(requestData, null, 2));
        console.log('API Key:', this.API_KEY.substring(0, 5) + '****');
        console.log('API URL:', this.API_BASE_URL);
        
        // 发起API请求
        uni.request({
          url: `${this.API_BASE_URL}/services/aigc/image2image/image-synthesis/`,
          method: 'POST',
          header: {
            'X-DashScope-Async': 'enable',
            'Authorization': `Bearer ${this.API_KEY}`,
            'Content-Type': 'application/json'
          },
          data: requestData,
          success: (res) => {
            console.log('===== 试衣API提交响应 =====');
            console.log('状态码:', res.statusCode);
            console.log('响应头:', JSON.stringify(res.header, null, 2));
            console.log('响应数据:', JSON.stringify(res.data, null, 2));
            
            if (res.data && res.data.output && res.data.output.task_id) {
              this.taskId = res.data.output.task_id;
              console.log('获取到任务ID:', this.taskId);
              // 轮询查询任务状态
              this.checkTaskStatus();
            } else {
              this.isGenerating = false;
              this.loading = false;
              console.error('提交任务失败, 没有获取到任务ID');
              uni.showToast({
                title: '提交任务失败',
                icon: 'none',
                duration: 2000
              });
            }
          },
          fail: (err) => {
            console.error('===== 试衣API调用失败 =====');
            console.error('错误详情:', JSON.stringify(err, null, 2));
            this.isGenerating = false;
            this.loading = false;
            uni.showToast({
              title: '网络请求失败',
              icon: 'none',
              duration: 2000
            });
          }
        });
      }, 800);
    },
    
    // 查询任务状态
    checkTaskStatus() {
      if (!this.taskId) return;
      
      console.log('===== 查询任务状态 =====');
      console.log('任务ID:', this.taskId);
      
      uni.request({
        url: `${this.API_BASE_URL}/tasks/${this.taskId}`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${this.API_KEY}`
        },
        success: (res) => {
          console.log('任务状态查询结果:', JSON.stringify(res.data, null, 2));
          
          if (res.data && res.data.output) {
            const status = res.data.output.task_status;
            console.log('任务状态:', status);
            
            if (status === 'SUCCEEDED') {
              // 任务成功
              console.log('任务成功完成，获取到图片URL:', res.data.output.image_url);
              this.completeProgress(); // 完成进度条
              this.loading = false;
              if (res.data.output.image_url) {
                this.generatedImage = res.data.output.image_url;
                
                // 显示成功动画
                setTimeout(() => {
                  this.isGenerating = false;
                  this.justGenerated = true;
                  this.showSuccessAnimation = true;
                  this.zoomAnimation = false; // 重置缩放状态
                  
                  // 保存试衣记录
                  this.saveTryOnRecord(res.data.output.image_url);
                }, 500); // 短暂延迟让进度条完成动画
              }
            } else if (status === 'FAILED') {
              // 清除进度条
              console.error('任务失败:', res.data.output.message || '未知错误');
              this.completeProgress();
              this.isGenerating = false;
              this.loading = false;
              uni.showToast({
                title: '试衣失败: ' + (res.data.output.message || '未知错误'),
                icon: 'none',
                duration: 3000
              });
            } else if (status === 'PENDING' || status === 'RUNNING') {
              // 任务仍在进行中，继续轮询
              console.log('任务仍在处理中，2秒后再次查询...');
              setTimeout(() => {
                this.checkTaskStatus();
              }, 2000); // 2秒后再次查询
            }
          } else {
            console.error('查询任务状态失败，响应数据格式不正确:', res.data);
            this.isGenerating = false;
            this.loading = false;
            uni.showToast({
              title: '查询任务状态失败',
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: (err) => {
          console.error('查询任务状态网络请求失败:', JSON.stringify(err, null, 2));
          this.isGenerating = false;
          this.loading = false;
          uni.showToast({
            title: '网络请求失败',
            icon: 'none',
            duration: 2000
          });
        }
      });
    },
    
    // 滚动到页面顶部
    scrollToTop() {
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 300
      });
    },
    
    // 预览图片
    previewImage(url) {
      if (!url) return;
      uni.previewImage({
        urls: [url],
        current: url,
        indicator: 'number',
        loop: false
      });
    },
    
    // 更换图片
    changeImage(type) {
      let that = this;
      that.$util.uploadImageChange('upload/image', (res) => {
        // 确保返回URL格式正确
        let imageUrl = res.data.url;
        
        // 检查URL是否以http开头
        if (imageUrl && imageUrl.indexOf('http') !== 0 && imageUrl.indexOf('//') !== 0) {
          // 直接使用完整URL
          imageUrl = getApp().globalData.HTTP_REQUEST_URL + '/' + imageUrl.replace(/^\/+/, '');
          console.log('完整上传URL:', imageUrl);
        }
        
        // 根据类型设置对应的图片并添加动画
        switch(type) {
          case 'top':
            that.isTopAnimating = true;
            that.selectedTopImage = imageUrl;
            setTimeout(() => {
              that.isTopAnimating = false;
            }, 1000);
            break;
          case 'bottom':
            that.isBottomAnimating = true;
            that.selectedBottomImage = imageUrl;
            setTimeout(() => {
              that.isBottomAnimating = false;
            }, 1000);
            break;
          case 'model':
            // 保存到本地存储，以便恢复
            try {
              uni.setStorageSync('ai_try_on_model', imageUrl);
            } catch (e) {
              console.error('保存模特图片到本地存储失败:', e);
            }
            that.personImage = imageUrl;
            
            // 重要修复：如果已经生成了效果图，切换模特时需要清除它
            if (that.generatedImage) {
              that.generatedImage = ''; // 清除已生成的效果图
              that.showSuccessAnimation = false; // 关闭成功动画
              that.justGenerated = false; // 重置生成状态
              
              // 显示切换提示
              uni.showToast({
                title: '已更换模特，请重新试穿',
                icon: 'none',
                duration: 2000
              });
            }
            break;
        }
        
        uni.showToast({
          title: '更换成功',
          icon: 'success'
        });
      }, (err) => {
        console.error('上传图片失败:', err);
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        });
      }, (size) => {
        // 图片尺寸回调
        console.log('图片尺寸:', size.w, size.h);
      });
    },
    
    // 开始进度条动画
    startProgressAnimation() {
      this.progressValue = 0;
      // 清除可能存在的旧定时器
      if (this.progressInterval) {
        clearInterval(this.progressInterval);
      }
      
      // 创建新的进度条动画
      this.progressInterval = setInterval(() => {
        // 进度条前进速度非线性，开始快，接近100%时变慢
        if (this.progressValue < 85) {
          this.progressValue += Math.random() * 2 + 1;
        } else if (this.progressValue < 95) {
          this.progressValue += Math.random() * 0.5 + 0.1;
        } else if (this.progressValue < 99) {
          this.progressValue += 0.05;
        }
        
        // 限制最大值为99%，等待实际完成
        if (this.progressValue > 99) {
          this.progressValue = 99;
        }
      }, 200);
    },
    
    // 完成进度条
    completeProgress() {
      // 清除定时器
      if (this.progressInterval) {
        clearInterval(this.progressInterval);
        this.progressInterval = null;
      }
      
      // 设置为100%
      this.progressValue = 100;
    },
    
    // 开始所有打字机动画
    startTypingAnimations() {
      // 如果不显示运势模块，则不启动打字机动画
      if (!this.showFortuneModules) return;
      
      // 清除可能存在的旧定时器
      if (this.luckTypingTimer) clearInterval(this.luckTypingTimer);
      
      // 开始桃花运势文字动画
      this.startLuckTextTyping();
    },
    
    // 桃花运势文字打字机动画
    startLuckTextTyping() {
      this.currentLuckText = '';
      this.luckTextIndex = 0;
      
      this.luckTypingTimer = setInterval(() => {
        if (this.luckTextIndex < this.luckDescription.length) {
          this.currentLuckText += this.luckDescription.charAt(this.luckTextIndex);
          this.luckTextIndex++;
        } else {
          clearInterval(this.luckTypingTimer);
        }
      }, 50); // 每50毫秒打一个字
    },
    
    // 图片加载错误处理
    handleImageError(type) {
      console.error(`图片加载失败: ${type}`, (type === 'model' ? this.personImage : (type === 'generated' ? this.generatedImage : '')));
      
      // 根据类型设置默认图片
      if (type === 'model') {
        // 检查URL是否是编码过的格式，如果是则尝试解码
        if (this.personImage && this.personImage.includes('%')) {
          try {
            // 尝试解码URL
            const decodedUrl = decodeURIComponent(this.personImage);
            console.log('尝试解码URL:', decodedUrl);
            
            if (decodedUrl !== this.personImage) {
              this.personImage = decodedUrl;
              return; // 尝试使用解码后的URL
            }
          } catch (e) {
            console.error('URL解码失败:', e);
          }
        }
        
        // 如果URL解码失败或不需要解码，使用本地默认图片
        // 使用绝对路径，确保在微信小程序中可以访问
        this.personImage = 'https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1760598171/p812706.png';
        console.log('已切换到默认模特图片');
      } else if (type === 'top') {
        this.selectedTopImage = 'https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1389646171/p801338.webp';
      } else if (type === 'bottom') {
        this.selectedBottomImage = 'https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1389646171/p801340.jpeg';
      } else if (type === 'generated') {
        // 如果生成的图片加载失败，清空URL，显示原始模特图片
        console.log('生成图片加载失败，清除生成图片并显示原始模特');
        this.generatedImage = '';
        this.showSuccessAnimation = false;
        this.justGenerated = false;
        this.isGenerating = false;
        
        // 确保模特图片有效
        if (!this.personImage) {
          this.personImage = 'https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1760598171/p812706.png';
        }
        
        uni.showToast({
          title: '图片生成失败',
          icon: 'none',
          duration: 2000
        });
      }
    },
    
    // 处理模特图片加载完成事件
    onModelImageLoad() {
      this.modelImageLoaded = true;
      console.log('模特图片加载完成');
    },
    
    // 保存试衣记录
    saveTryOnRecord(imageUrl) {
      // 避免重复保存
      if (this.recordSaved) return;
      
      console.log('准备保存试衣记录...');
      console.log('生成图片URL:', imageUrl);
      console.log('上衣图片URL:', this.selectedTopImage);
      
      // 打印当前用户信息
      console.log('当前用户信息:');
      console.log('uid:', uni.getStorageSync('uid'));
      console.log('nickname:', uni.getStorageSync('nickname'));
      console.log('phone:', uni.getStorageSync('phone'));
      console.log('token:', uni.getStorageSync('token'));
      
      const randomUid = uni.getStorageSync('uid');
      
      // 确保图片URL是有效的
      const validImageUrl = this.ensureValidUrl(imageUrl);
      const validClothesUrl = this.ensureValidUrl(this.selectedTopImage);
      
      console.log('处理后的生成图片URL:', validImageUrl);
      console.log('处理后的上衣图片URL:', validClothesUrl);
      
      // 根据图片中的格式构建记录数据
      const recordData = {
        uid: randomUid,
        nickname: uni.getStorageSync('nickname') || '',
        phone: uni.getStorageSync('phone') || '',
        title: this.modelParams.style ? `${this.modelParams.style}穿搭` : '今日穿搭',
        icon: '/icons/default.png',
        image_url: validImageUrl,
        des: this.analysisText || '我的试衣记录',
        suitable: this.suitableTags.join('、'),
        not_suitable: this.notSuitableTags.join('、'),
        clothes_url: validClothesUrl
      };
      
      console.log('试衣记录数据:', JSON.stringify(recordData, null, 2));

      // 使用项目实际的API域名
      const apiBaseUrl = 'https://test.zysemtime.com';
      
      // 获取全局配置的URL，如果为空则使用硬编码值
      const globalBaseUrl = getApp().globalData.HTTP_REQUEST_URL;
      console.log('全局配置的基础URL:', globalBaseUrl);
      
      // 如果全局URL存在，则使用全局URL，否则使用硬编码的URL
      const fullApiUrl = globalBaseUrl ? (globalBaseUrl + '/api/dress_history/add') : (apiBaseUrl + '/api/dress_history/add');
      console.log('使用的完整API URL:', fullApiUrl);
      
      uni.request({
        url: fullApiUrl,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': uni.getStorageSync('token') // 添加授权头，确保API能识别用户
        },
        data: recordData,
        success: (res) => {
          console.log('保存试衣记录响应:', JSON.stringify(res.data, null, 2));
          
          // 处理响应结果，根据图片中的格式调整
          if (res.data && res.data.code === 200) {
            this.recordSaved = true;
            
            // 设置全局标记，告诉history页面需要刷新数据
            getApp().globalData.needRefreshHistory = true;
            console.log('已设置全局刷新标记：needRefreshHistory = true');
            
            uni.showToast({
              title: '已保存至试衣记录',
              icon: 'success',
              duration: 2000
            });
          } else {
            console.error('保存试衣记录失败, 错误详情:', JSON.stringify(res.data, null, 2));
            uni.showToast({
              title: res.data?.message || '保存记录失败',
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: (err) => {
          console.error('保存试衣记录请求失败:', err);
          console.error('错误详情:', JSON.stringify(err, null, 2));
          
          uni.showToast({
            title: '网络请求失败，请稍后再试',
            icon: 'none',
            duration: 2000
          });
        }
      });
    },
    
    // 确保URL有效
    ensureValidUrl(url) {
      if (!url) return '';
      
      console.log('处理URL:', url);
      
      // 如果URL已经是完整URL，直接返回
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url;
      }
      
      // 如果URL是相对路径，添加基础URL
      const baseUrl = getApp().globalData.HTTP_REQUEST_URL || 'https://test.zysemtime.com';
      const formattedUrl = url.startsWith('/') ? url.substring(1) : url;
      return `${baseUrl}/${formattedUrl}`;
    },
    
    
    // 获取商品类型，用于试穿功能
    getItemType(item, index) {
      // 如果商品本身有类型信息，则使用它
      if (item.item_type) {
        return item.item_type;
      }
      
      // 根据商品名称判断类型
      const name = item.name || '';
      if (name.includes('裙') || name.includes('裤') || name.includes('下装')) {
        return 'bottom';
      }
      
      // 根据索引决定默认类型（奇数为下装，偶数为上装）
      return index % 2 === 1 ? 'bottom' : 'top';
    },
    // 跳转到new_tryai页面
    goToNewTryAI() {
      uni.navigateTo({
        url: '/pages/AI_try_on/home_page'
      });
    },
    // 跳转到try_on_detail页面
    goToTryOnDetail() {
      uni.navigateTo({
        url: '/pages/AI_try_on/try_on_detail'
      });
    },
    
    // 测试穿搭推荐API异步模式
    testFashionRecommend() {
      if (this.fashionLoading) {
        console.log('正在处理中，请等待...');
        return;
      }
      
      this.fashionLoading = true;
      console.log('===== 测试穿搭推荐API (异步) =====');
      
      // 获取账号
      const account = uni.getStorageSync('uid') || uni.getStorageSync('account') || '';
      console.log('使用账号:', account);
      
      // 构建请求参数 - 只在请求头中包含账号
      const data = {
        user_input: "我希望有一套适合在运动场所的服装，我是女性，1990年3月出生",
        user_info: {
          // 移除account字段
          user_id: "test123",
          name: "测试用户",
          gender: "女",
          birth_date: "1990-03-15",
          height: 165,
          weight: 55,
          body_shape: "标准"
        }
      };
      
      console.log('请求参数:', JSON.stringify(data, null, 2));
      console.log('Authorization头:', `Bearer ${account}`);
      
      // 发起请求
      getFashionRecommend(data).then(res => {
        console.log('穿搭推荐提交响应:', JSON.stringify(res, null, 2));
        this.fashionLoading = false;
        
        if (res.result_code === 200 && res.data && res.data.request_id) {
          this.fashionRequestId = res.data.request_id;
          console.log('获取到请求ID:', this.fashionRequestId);
          
          // 开始轮询查询状态
          this.startFashionStatusPolling();
          
          // 显示成功提示
          uni.showToast({
            title: '请求已提交',
            icon: 'success',
            duration: 2000
          });
        } else if (res.result_code === 401) {
          // 处理认证错误
          console.error('认证失败:', res.message || '无效的账号或用户未登录');
          uni.showToast({
            title: '认证失败: ' + (res.message || '账号无效'),
            icon: 'none',
            duration: 2000
          });
        } else {
          console.error('提交失败:', res.message || '未知错误');
          uni.showToast({
            title: '请求失败: ' + (res.message || '未知错误'),
            icon: 'none',
            duration: 2000
          });
        }
      }).catch(err => {
        this.fashionLoading = false;
        console.error('穿搭推荐提交失败:', err);
        uni.showToast({
          title: '网络请求失败',
          icon: 'none',
          duration: 2000
        });
      });
    },
    
    // 开始轮询查询穿搭推荐状态
    startFashionStatusPolling() {
      // 清除可能存在的旧定时器
      if (this.fashionPollingTimer) {
        clearInterval(this.fashionPollingTimer);
      }
      
      // 设置轮询间隔为3秒
      this.fashionPollingTimer = setInterval(() => {
        this.checkFashionStatus();
      }, 3000);
    },
    
    // 查询穿搭推荐状态
    checkFashionStatus() {
      if (!this.fashionRequestId) {
        console.error('没有可用的请求ID');
        return;
      }
      
      console.log('===== 查询穿搭推荐状态 =====');
      console.log('请求ID:', this.fashionRequestId);
      
      getFashionStatus(this.fashionRequestId).then(res => {
        console.log('穿搭推荐状态响应:', res);
        
        // 添加详细JSON打印
        console.log('状态查询完整响应:');
        console.log(JSON.stringify(res, null, 2));
        
        if (res.result_code === 200 && res.data && res.data.status) {
          const status = res.data.status;
          console.log('处理状态:', status);
          
          if (status === 'succeed') {
            // 处理成功，清除轮询定时器
            clearInterval(this.fashionPollingTimer);
            this.fashionPollingTimer = null;
            this.fashionLoading = false;
            
            // 保存返回的数据
            this.fashionData = res.data.result;
            console.log('穿搭推荐数据:', this.fashionData);
            
            // 使用新增加的方法处理API返回的运势和穿搭数据
            this.processApiResponse(res);
            
            // 提交评分示例
            // this.testSubmitRating();
          } else if (status === 'fail') {
            // 处理失败，清除轮询定时器
            clearInterval(this.fashionPollingTimer);
            this.fashionPollingTimer = null;
            this.fashionLoading = false;
            
            console.error('穿搭推荐处理失败');
            } else {
            // 继续等待处理
            console.log('穿搭推荐处理中，继续等待...');
          }
        } else {
          console.error('状态查询响应数据格式不正确');
        }
      }).catch(err => {
        console.error('状态查询失败:', err);
      });
    },
    
    // 测试提交评分
    testSubmitRating() {
      if (!this.fashionRequestId) {
        console.error('没有可用的请求ID');
        return;
      }
      
      console.log('===== 测试提交穿搭推荐评分 =====');
      
      const data = {
        request_id: this.fashionRequestId,
        rating: 5
      };
      
      console.log('评分参数:', data);
      
      submitFashionRating(data).then(res => {
        console.log('评分提交响应:', res);
        if (res.result_code === 200) {
          console.log('评分提交成功');
        } else {
          console.error('评分提交失败:', res.message);
        }
      }).catch(err => {
        console.error('评分提交失败:', err);
      });
    },
    
    // 处理穿搭推荐API返回数据
    handleFashionData(data) {
      console.log('处理穿搭推荐数据:', data);
      
      if (!data || !data.result) {
        console.error('无效的穿搭数据');
        return;
      }
      
      const result = data.data.result;
      
      // 处理运势概览数据
      if (result.fortune_overview) {
        // 保存全部运势文本
        this.luckDescription = result.fortune_overview.yearly_overview || '';
        
        // 如果有年度概览和建议，合并显示
        let fullDescription = '';
        if (result.fortune_overview.yearly_overview) {
          fullDescription += result.fortune_overview.yearly_overview;
        }
        if (result.fortune_overview.general_advice) {
          if (fullDescription) fullDescription += '\n\n';
          fullDescription += result.fortune_overview.general_advice;
        }
        
        this.currentLuckText = fullDescription || '暂无运势数据';
      }
      
      // 处理幸运色数据
      if (result.lucky_color) {
        this.luckyColorMain = {
          name: result.lucky_color.main_color || '蓝色',
          color: this.getColorGradient(result.lucky_color.main_color),
          textColor: this.getColorCode(result.lucky_color.main_color) || '#4a90e2'
        };
        
        this.luckyColorAssist = {
          name: result.lucky_color.auxiliary_color || '白色',
          color: this.getColorGradient(result.lucky_color.auxiliary_color),
          textColor: this.getColorCode(result.lucky_color.auxiliary_color) || '#ffffff'
        };
        
        this.luckyColorDesc = '增强运势，调和元素，提升个人气场';
      }
      
      // 处理运势指数数据
      if (result.lucky_elements) {
        this.fortuneStar = this.getAverageStar(result.lucky_elements);
        
        this.fortuneIndexList = [
          {
            type: 'love',
            label: '爱情运',
            stars: result.lucky_elements.love || 3,
            desc: '提升桃花运势，提高异性缘'
          },
          {
            type: 'career',
            label: '事业运',
            stars: result.lucky_elements.career || 3,
            desc: '工作顺利，有升职加薪机会'
          },
          {
            type: 'health',
            label: '健康运',
            stars: result.lucky_elements.health || 3,
            desc: '身体健康，注意作息规律'
          }
        ];
      }
      
      // 处理穿搭建议数据
      if (result.outfit_suggestion) {
        // 更新推荐的颜色标签
        const colors = result.outfit_suggestion.recommended_colors || [];
        const colorTags = colors.map(color => {
          return {
            text: color,
            className: 'color ' + this.getColorClass(color)
          };
        });
        
        // 更新推荐的风格标签
        const styles = result.outfit_suggestion.styles || [];
        const styleTags = styles.map(style => {
          return {
            text: style,
            className: 'style ' + this.getStyleClass(style)
          };
        });
        
        // 更新推荐的服装类型标签
        const types = result.outfit_suggestion.clothing_types || [];
        const typeTags = types.map(type => {
          return {
            text: type,
            className: 'type fabric'
          };
        });
        
        // 设置标签数据
        this.wearTags = {
          colors: colorTags,
          styles: styleTags,
          types: typeTags
        };
      }
      
      // 显示成功提示
      uni.showToast({
        title: '穿搭推荐已更新',
        icon: 'success',
        duration: 2000
      });
    },
    
    // 获取颜色对应的CSS颜色代码
    getColorCode(colorName) {
      const colorMap = {
        '蓝色': '#4a90e2',
        '白色': '#ffffff',
        '灰色': '#9e9e9e',
        '黑色': '#333333',
        '红色': '#f44336',
        '粉色': '#e91e63',
        '紫色': '#9c27b0',
        '绿色': '#4caf50',
        '黄色': '#ffeb3b',
        '橙色': '#ff9800',
        '棕色': '#795548'
      };
      
      return colorMap[colorName] || '#4a90e2';
    },
    
    // 获取颜色对应的CSS类名
    getColorClass(colorName) {
      const colorClassMap = {
        '蓝色': 'blue',
        '白色': 'white',
        '灰色': 'silver',
        '黑色': 'black',
        '红色': 'red',
        '粉色': 'pink',
        '紫色': 'purple',
        '绿色': 'green',
        '黄色': 'yellow',
        '橙色': 'orange',
        '棕色': 'brown'
      };
      
      return colorClassMap[colorName] || 'blue';
    },
    
    // 获取风格对应的CSS类名
    getStyleClass(styleName) {
      const styleClassMap = {
        '舒适': 'comfort',
        '运动风': 'sports',
        '休闲': 'casual',
        '商务': 'business',
        '复古': 'retro',
        '优雅': 'elegant',
        '时尚': 'fashion'
      };
      
      return styleClassMap[styleName] || 'comfort';
    },
    
    // 计算平均星级
    getAverageStar(elements) {
      if (!elements) return 3;
      
      const values = Object.values(elements);
      if (values.length === 0) return 3;
      
      const sum = values.reduce((acc, val) => acc + val, 0);
      return Math.round(sum / values.length);
    },
    
    // 检查API URL是否正确
    checkApiUrls() {
      // 获取账号
      const account = uni.getStorageSync('uid') || uni.getStorageSync('account') || '';
      
      console.log('===== 检查API URL =====');
      console.log('Fashion API URL:', `${this.FASHION_API_URL}/api/fashion`);
      console.log('Health API URL:', `${this.FASHION_API_URL}/api/health`);
      console.log('Authorization Header:', `Bearer ${account}`);
    },

    // 测试模拟API数据
    testMockFashionData() {
      const mockData = {
        "data": {
          "request_id": "40aecf17-51cc-45d5-9d28-98e495e6e07e",
          "result": {
            "fortune_overview": {
              "general_advice": "保持乐观的心态，增强体质，积极参与运动，能够吸引更多正能量。",
              "yearly_overview": "2023年是一个充满机遇和挑战的一年，注重健康和积极锻炼将有助于提升整体运势。"
            },
            "lucky_color": {
              "auxiliary_color": "白色",
              "main_color": "蓝色"
            },
            "lucky_elements": {
              "career": 3,
              "health": 5,
              "love": 4
            },
            "outfit_suggestion": {
              "clothing_types": [
                "运动上衣（如速干T恤）",
                "运动裤（如瑜伽裤或慢跑裤）",
                "运动外套（如轻便风衣）",
                "舒适运动鞋"
              ],
              "recommended_colors": [
                "蓝色",
                "白色",
                "灰色"
              ],
              "styles": [
                "舒适",
                "运动风",
                "休闲"
              ]
            }
          },
          "status": "succeed"
        },
        "message": "处理完成",
        "result_code": 200
      };
      
      // 调用处理方法
      this.handleFashionData(mockData.data);
    },

    // 获取颜色渐变
    getColorGradient(colorName) {
      const gradientMap = {
        '蓝色': 'linear-gradient(135deg, #e0eafc, #cfdef3)',
        '白色': 'linear-gradient(135deg, #ffffff, #f5f5f5)',
        '灰色': 'linear-gradient(135deg, #cfd9df, #e2ebf0)',
        '黑色': 'linear-gradient(135deg, #434343, #000000)',
        '红色': 'linear-gradient(135deg, #ff9a9e, #fad0c4)',
        '粉色': 'linear-gradient(135deg, #fbc2eb, #a6c1ee)',
        '紫色': 'linear-gradient(135deg, #a1c4fd, #c2e9fb)',
        '绿色': 'linear-gradient(135deg, #a8edea, #fed6e3)',
        '黄色': 'linear-gradient(135deg, #f6d365, #fda085)',
        '橙色': 'linear-gradient(135deg, #ffecd2, #fcb69f)',
        '棕色': 'linear-gradient(135deg, #e6b980, #eacda3)'
      };
      
      return gradientMap[colorName] || 'linear-gradient(135deg, #e0eafc, #cfdef3)';
    },
    
    // 处理运势数据
    handleFortuneData(data) {
      console.log('处理运势数据:', data.data.result);
      
      // 添加更详细的JSON打印
      console.log('完整JSON数据:');
      console.log(JSON.stringify(data, null, 2));
      
      if (!data || !data.data || !data.data.result) {
        console.error('无效的运势数据');
        return;
      }
      
      // 保存原始数据
      this.fortuneData = data;
      const result = data.data.result;
      
      // 1. 处理年度运势
      if (result.year_fortune) {
        // 解析运势标题
        const yearData = result.year_fortune;
        
        // 解析流年干支信息
        const subTitle = yearData.sub_title || '';
        console.log('解析流年干支原始数据:', subTitle);
        
        // 提取流年干支和描述
        let liuNianText = '乙己年';
        let liuNianDesc = '木火相生';
        
        // 先尝试去除所有流年干支相关的标记文本，避免重复
        let cleanSubTitle = subTitle;
        cleanSubTitle = cleanSubTitle.replace(/\*\*\*流年干支:\*\*\*\//, '');
        cleanSubTitle = cleanSubTitle.replace(/流年干支:/, '');
        console.log('清理后的流年干支文本:', cleanSubTitle);
        
        // 尝试多种匹配模式
        // 第一种格式: **乙己年**/*木火相声*
        let liuNianMatch = cleanSubTitle.match(/\*\*([^*]+)\*\*\/\*([^*]+)\*/);
        if (liuNianMatch && liuNianMatch.length > 2) {
          console.log('匹配到格式1 - 流年干支:', liuNianMatch[1], '描述:', liuNianMatch[2]);
          liuNianText = liuNianMatch[1];
          liuNianDesc = liuNianMatch[2];
            } else {
          // 第二种格式: 分别匹配**乙己年**和*木火相声*
          const yearMatch = cleanSubTitle.match(/\*\*([^*]+)\*\*/);
          if (yearMatch && yearMatch[1]) {
            console.log('匹配到格式2 - 流年干支:', yearMatch[1]);
            liuNianText = yearMatch[1];
          }
          
          const descMatch = cleanSubTitle.match(/\*([^*]+)\*/);
          if (descMatch && descMatch[1]) {
            console.log('匹配到格式2 - 描述:', descMatch[1]);
            liuNianDesc = descMatch[1];
          }
        }
        
        console.log('最终解析结果 - 流年文本:', liuNianText, '流年描述:', liuNianDesc);
        
        this.yearFortune = {
          title: yearData.title || '2025年运势解析',
          liuNianText: liuNianText,
          liuNianDesc: liuNianDesc,
          description: yearData.description || '暂无年度运势数据'
        };
        
        // 更新打字机效果的文本
        this.luckDescription = yearData.description || '';
        this.currentLuckText = ''; // 清空当前文本，以便重新开始打字效果
        
        // 启动打字机动画
        this.startLuckTextTyping();
      }
      
      // 2. 处理综合运势
      if (result.overall_fortune) {
        const overallData = result.overall_fortune;
        this.overallFortune = {
          title: overallData.title || '2025年综合运势',
          star: parseInt(overallData.star) || 4,
          description: overallData.description || '事业与财运机遇突出，健康需稍加留意。'
        };
        
        // 更新综合运势星级
        this.fortuneStar = parseInt(overallData.star) || 4;
      }
      
      // 3. 处理幸运色
      if (result.lucky_color) {
        const colorData = result.lucky_color;
        
        // 解析主色
        let mainColorCode = '#4B5320';
        let mainColorName = '军绿色';
        
        const mainColorMatch = colorData.main_color.match(/\*\*([^*]+)\*\*\/\*([^*]+)\*\//);
        if (mainColorMatch && mainColorMatch.length > 2) {
          mainColorCode = mainColorMatch[1];
          mainColorName = mainColorMatch[2];
        }
        
        // 解析辅助色
        let assistColorCode = '#FFD700';
        let assistColorName = '金色';
        
        const assistColorMatch = colorData.assist_color.match(/\*\*([^*]+)\*\*\/\*([^*]+)\*\//);
        if (assistColorMatch && assistColorMatch.length > 2) {
          assistColorCode = assistColorMatch[1];
          assistColorName = assistColorMatch[2];
        }
        
        this.luckyColorMain = {
          name: mainColorName,
          textColor: mainColorCode
        };
        
        this.luckyColorAssist = {
          name: assistColorName,
          textColor: assistColorCode
        };
        
        this.luckyColorDesc = colorData.description || '增强木行气场，调和火气，助事业与健康';
      }
      
      // 4. 处理运势指数
      if (result.lucky_elements) {
        const elementsData = result.lucky_elements;
        
        // 创建新的运势指数列表
        const newFortuneIndexList = [];
        
        // 处理爱情运势
        if (elementsData.love_fortune) {
          const loveMatch = elementsData.love_fortune.match(/([^*]+)\*\*star:(\d+)\*\*(.+)/);
          if (loveMatch && loveMatch.length > 3) {
            newFortuneIndexList.push({
              type: 'love',
              label: loveMatch[1].trim(),
              stars: parseInt(loveMatch[2]) || 4,
              desc: loveMatch[3].trim()
            });
          }
        }
        
        // 处理事业运势
        if (elementsData.career_fortune) {
          const careerMatch = elementsData.career_fortune.match(/([^*]+)\*\*star:(\d+)\*\*(.+)/);
          if (careerMatch && careerMatch.length > 3) {
            newFortuneIndexList.push({
              type: 'career',
              label: careerMatch[1].trim(),
              stars: parseInt(careerMatch[2]) || 4,
              desc: careerMatch[3].trim()
            });
          }
        }
        
        // 处理健康运势
        if (elementsData.health_fortune) {
          const healthMatch = elementsData.health_fortune.match(/([^*]+)\*\*star:(\d+)\*\*(.+)/);
          if (healthMatch && healthMatch.length > 3) {
            newFortuneIndexList.push({
              type: 'health',
              label: healthMatch[1].trim(),
              stars: parseInt(healthMatch[2]) || 3,
              desc: healthMatch[3].trim()
            });
          }
        }
        
        // 只有在成功解析了数据的情况下才更新
        if (newFortuneIndexList.length > 0) {
          this.fortuneIndexList = newFortuneIndexList;
        }
      }
      
      // 5. 处理穿搭建议
      if (result.outfit_suggestion) {
        const outfitData = result.outfit_suggestion;
        
        // 处理服装风格
        const styles = outfitData.clothing_styles || [];
        const styleTags = styles.map(style => {
          return {
            text: style,
            className: 'style ' + this.getStyleClass(style)
          };
        });
        
        // 处理服装类型
        const types = outfitData.clothing_types || [];
        const typeTags = types.map(type => {
          return {
            text: type,
            className: 'type fabric'
          };
        });
        
        // 更新标签数据
        this.wearTags = {
          colors: this.wearTags.colors, // 保留原有颜色标签
          styles: styleTags,
          types: typeTags
        };
      }
      
      // 6. 处理重点月份提示
      if (result.key_month_tips && result.key_month_tips.tips) {
        this.monthTipsList = result.key_month_tips.tips.map(item => {
          return {
            month: item.month,
            tip: item.tip
          };
        });
      }
      
      // 显示成功提示
      uni.showToast({
        title: '运势数据已更新',
        icon: 'success',
        duration: 2000
      });
    },
    
    // 添加一个测试解析的方法
    testParseFortuneData() {
      // 测试数据
      const testData = {
        "data": {
          "request_id": "a03d0a91-a644-4893-b0f1-18376f37c76a",
          "result": {
            "key_month_tips": {
              "tips": [
                {
                  "month": "5月",
                  "tip": "事业突破期，穿军绿色增强气场"
                },
                {
                  "month": "8月",
                  "tip": "健康关键期，注意饮食和运动"
                },
                {
                  "month": "10月",
                  "tip": "感情升温期，金色系提升魅力"
                }
              ],
              "title": "2025年重点月份提示"
            },
            "lucky_color": {
              "assist_color": "**#FFD700**/*金色*/",
              "description": "增强木行气场，调和火气，助事业与健康",
              "main_color": "**#4B5320**/*军绿色*/",
              "title": "个人幸运色"
            },
            "lucky_elements": {
              "career_fortune": "事业运**star:4**户外或自然相关领域有突破，特别是5-6月",
              "health_fortune": "健康运**star:3**需注意体重管理和户外活动安全",
              "love_fortune": "桃花运**star:4**春季和秋季易有户外活动中的浪漫邂逅",
              "title": "2025年运势指数"
            },
            "outfit_suggestion": {
              "clothing_styles": [
                "户外运动",
                "休闲舒适"
              ],
              "clothing_types": [
                "透气快干面料(适合爬山)",
                "带有金属配饰的运动鞋(提升运势)"
              ],
              "title": "建议穿搭标签"
            },
            "overall_fortune": {
              "description": "事业与健康机遇并存，感情运势良好",
              "star": "4",
              "title": "2025年综合运势"
            },
            "year_fortune": {
              "description": "2025年，日主辛金(阴金)生于乙己年，木火相生，形成「木火通明」格局。本年事业上将有新的机遇，特别是在户外活动或与自然相关的领域。健康方面需注意体重管理，避免因肥胖引起的健康问题。感情上，单身的你有机会在户外活动中遇到志同道合的伴侣。",
              "sub_title": "***流年干支:***/**乙己年**/*木火相声*",
              "title": "2025年运势解析"
            }
          },
          "status": "succeed"
        },
        "message": "处理完成",
        "result_code": 200
      };
      
      // 打印测试数据
      console.log('测试数据JSON:');
      console.log(JSON.stringify(testData, null, 2));
      
      // 调用解析方法
      this.handleFortuneData(testData);
    },
    openClothesUploadNotice(type) {
      const localKey = type === 'top' ? 'hideClothesUploadNoticeModal_home_top' : 'hideClothesUploadNoticeModal_home_bottom';
      if (uni.getStorageSync(localKey)) {
        this.handleClothesUploadAgree(true);
        return;
      }
      this.clothesUploadLocalKey = localKey;
      this.clothesUploadType = type;
      this.showClothesUploadNotice = true;
    },
    handleClothesUploadAgree(checked) {
      this.showClothesUploadNotice = false;
      // 弹窗同意后，继续原有的上传逻辑
      this.changeImage(this.clothesUploadType);
    },
    handleClothesUploadDisagree() {
      this.showClothesUploadNotice = false;
    },
    openUploadNoticeModal() {
      const localKey = 'hideUploadNoticeModal_home_model';
      if (uni.getStorageSync(localKey)) {
        this.handleUploadAgree(true);
        return;
      }
      this.uploadNoticeLocalKey = localKey;
      this.showUploadNotice = true;
    },
  }
}
</script>

<style lang="scss" scoped>
// 主容器
.recommendation-container {
  display: flex;
  flex-direction: column;
  // 改回高级感渐变浅粉色背景
  background: linear-gradient(150deg, #fff9fb, #ffecf3, #fedfeb);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  min-height: 100vh;
  position: relative; // 确保定位上下文
  
}

// 顶部区域，包含状态栏和导航栏
.header-area {
  position: fixed; // 固定定位
  top: 0;
  left: 0;
  right: 0;
  z-index: 999; // 确保在最上层
  // 更美观的渐变
  background: linear-gradient(120deg, #ff5b9a, #a85ce0);
}

// 顶部状态栏
.status-bar {
  width: 100%;
}

// 导航栏
.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  height: 50px; // 明确设置导航栏高度
  
  .back-btn {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .back-icon {
      width: 22px;
      height: 22px;
      opacity: 0.9; // 更微妙的透明度
    }
  }
  
  .page-title {
    color: #fff;
    font-size: 18px;
    font-weight: 600; // 减轻粗体
    letter-spacing: 1px; // 增加字间距
  }
  
  .placeholder-btn {
    width: 40px;
    height: 40px;
  }
}

// 内容区域
.content-area {
  // paddingTop通过动态绑定添加，以匹配状态栏+导航栏的高度
  display: flex;
  flex-direction: column;
  padding-bottom: 30px; // 减小底部内边距，不再为按钮预留空间
}

// 运势模块
.fortune-card {
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 6px 24px rgba(168,92,224,0.10);
  padding: 22px 18px 18px 18px;
  margin: 8px 0;
  .luck-title {
    color: #ff5b9a;
    font-size: 22px;
    font-weight: bold;
    letter-spacing: 1px;
    text-align: left;
    display: block;
    margin-bottom: 8px;
  }
  .liunian-tag-row {
    display: flex;
    align-items: center;
    margin-top: 6px;
    margin-bottom: 10px;
    gap: 4px;
  }
  .liunian-label {
    font-size: 18px;
    font-weight: bold;
    color: #a85ce0;
    letter-spacing: 1px;
  }
  .liunian-value {
    font-size: 16px;
    font-weight: bold;
    color: #ff5b9a;
    letter-spacing: 1px;
  }
  .liunian-desc {
    font-size: 15px;
    color: #b39ddb;
    font-style: italic;
    margin-left: 2px;
  }
  .luck-description {
    color: #444;
    font-size: 15px;
    line-height: 1.8;
    margin-top: 8px;
    white-space: pre-line;
    font-weight: 400;
    overflow: visible;
    max-height: none;
    word-break: break-word;
    padding-bottom: 10px;
    display: block;
    width: 100%;
  }
}

// 试穿预览区
.preview-section {
  background-color: #fff;
  margin: 0;
  padding: 0;
  border-radius: 0;
  box-shadow: none;

  .image-comparison {
    display: flex;
    justify-content: space-between;
    margin: 15px;
    height: 320px; // 增加高度

    .left-column {
      width: 48%;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      
      .image-placeholder {
        width: 100%;
        height: 48%;
        border: none; // 移除边框
        border-radius: 12px; // 增加圆角
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #fff; // 纯白背景
        overflow: hidden;
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15); // 加深阴影
        
        &.upper {
          margin-bottom: 5px;
        }
        
        &.lower {
          margin-top: 5px;
        }
        
        .placeholder-text {
          color: #999; // 更柔和的颜色
          font-size: 16px;
          font-weight: 500; // 减轻粗体
        }
        
        .preview-image {
          width: 100%;
          height: 100%;
          object-fit: contain;
        }
      }
    }
    
    .right-column {
      width: 48%;
      height: 100%;
      transform-origin: center;
      transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
      
      .image-placeholder {
        width: 100%;
        height: 100%;
        border: none; // 移除边框
        border-radius: 12px; // 增加圆角
        display: flex;
        justify-content: center;
        align-items: center;
        background: linear-gradient(145deg, #fff, #f8f8f8); // 微妙渐变背景
        overflow: hidden;
        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.18); // 加深模特展示区阴影
        
        .placeholder-text {
          color: #999; // 更柔和的颜色
          font-size: 16px;
          font-weight: 500; // 减轻粗体
        }
        
        .preview-image {
          width: 100%;
          height: 100%;
          object-fit: contain;
        }
      }
    }
  }

  .try-btns-row {
    display: flex;
    flex-direction: row;
    gap: 24rpx;
    margin-top: 20rpx;
    margin-bottom: 20rpx;
    width: 100%;
    justify-content: center;
  }
  .try-on-button, .try-now-button {
    flex: 1;
    height: 90rpx;
    border-radius: 45rpx;
    font-size: 32rpx;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;
    border: none;
    transition: all 0.18s cubic-bezier(0.4,0,0.2,1);
    position: relative;
    overflow: hidden;
  }
  .try-on-button {
    background: linear-gradient(90deg, #ff7eb3 0%, #ff4d8d 100%);
    color: #fff;
    box-shadow: 0 6rpx 16rpx rgba(255, 92, 141, 0.18);
    margin-right: 0;
  }
  .try-on-button:active:not(.button-disabled) {
    transform: translateY(2px) scale(0.98);
    box-shadow: 0 3rpx 8rpx rgba(255, 92, 141, 0.18);
  }
  .try-now-button {
    background: linear-gradient(90deg, #ff7eb3 0%, #ff4d8d 100%);
    color: #fff;
    box-shadow: 0 6rpx 16rpx rgba(77, 141, 255, 0.18);
    margin-left: 0;
  }
  .try-now-button:active {
    transform: translateY(2px) scale(0.98);
    box-shadow: 0 3rpx 8rpx rgba(77, 141, 255, 0.18);
  }
  .try-on-button text, .try-now-button text {
    font-size: 32rpx;
    font-weight: bold;
    color: #fff;
    text-shadow: 0 2rpx 8rpx rgba(51,51,102,0.08);
  }
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  display: block;
}



.fortune-section {
  background-color: #fff;
  margin: 0;
  padding: 20px 15px; // 增加垂直内边距
  border-radius: 0;
  box-shadow: none;
  border-top: 1px solid #f0f0f0;

  .section-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 18px;
    color: #333;
    letter-spacing: 0.5px;
  }

  .fortune-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 14px;
    font-size: 14px;

    .star-rating {
      width: 65%; // 增加宽度
      position: relative;
      height: 20px; // 增加高度

      .rating-bar {
        height: 5px; // 稍微加粗
        position: absolute;
        bottom: 0;
        left: 0;
        border-radius: 2.5px; // 圆角匹配高度

        &.pink {
          background: linear-gradient(90deg, #ff3366, #ff6699); // 添加渐变
        }

        &.purple {
          background: linear-gradient(90deg, #9c27b0, #ba68c8); // 添加渐变
        }

        &.blue {
          background: linear-gradient(90deg, #2196f3, #64b5f6); // 添加渐变
        }
      }

      .stars-text {
        position: absolute;
        top: -5px;
        left: 0;
        width: 100%;
        text-align: left;
        font-size: 14px;
        color: #ff5b9a; // 匹配主题色
        letter-spacing: 1px; // 星星间距
      }
    }
  }
}

// 推荐商品部分
.recommendation-list-section {
  background-color: #fff;
  margin: 8px 0;
  padding: 14px 10px; // 增加垂直内边距
  border-radius: 0;
  box-shadow: none;
  border-top: 1px solid #f0f0f0;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 18px;

    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      letter-spacing: 0.5px;
    }

    .view-all {
      font-size: 12px;
      color: #999;
      padding: 3px 10px;
      border-radius: 12px;
      background-color: #f5f5f5;
    }
  }

  .recommendation-item {
    display: flex;
    margin-bottom: 18px;
    padding-bottom: 18px;
    border-bottom: 1px solid #f0f0f0; // 更淡的分隔线

    &:last-child {
      border-bottom: none;
      margin-bottom: 0;
      padding-bottom: 0;
    }

    // 图片占位符
    .item-image-placeholder {
      width: 80px;
      height: 100px;
      border-radius: 8px; // 更大的圆角
      margin-right: 15px;
      flex-shrink: 0;
      background-color: #fafafa;
      border: 1px dashed rgba(0, 0, 0, 0.1);
      display: flex;
      justify-content: center;
      align-items: center;
      color: #999;
      font-size: 12px;
      overflow: hidden; // 确保图片不会溢出容器
      
      .item-image {
        width: 100%;
        height: 100%;
        object-fit: cover; // 图片填充容器
      }
    }

    .item-details {
      flex-grow: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .item-name {
        font-size: 14px;
        font-weight: 600;
        margin-bottom: 4px;
        color: #333; // 更深的文字颜色
      }

      .item-description {
        font-size: 12px;
        color: #666;
        margin-bottom: 10px;
        line-height: 1.5;
      }

      .item-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 6px;

        .tag {
          font-size: 10px;
          padding: 2px 8px;
          border-radius: 10px;
          border: none; // 移除边框
          background-color: #f5f5f5; // 统一背景色
          color: #666; // 统一文字颜色

          &.recommended {
            color: #ff3366;
            background-color: rgba(255, 51, 102, 0.1); // 半透明背景
          }
          &.hot {
            color: #ff5722;
            background-color: rgba(255, 87, 34, 0.1);
          }
          &.style {
            color: #4caf50;
            background-color: rgba(76, 175, 80, 0.1);
          }
          &.new {
            color: #2196f3;
            background-color: rgba(33, 150, 243, 0.1);
          }
          &.luck {
            color: #ff9800;
            background-color: rgba(255, 152, 0, 0.1);
          }
          &.discount {
            color: #9c27b0;
            background-color: rgba(156, 39, 176, 0.1);
          }
        }
      }
    }

    .item-action {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      justify-content: space-between;
      margin-left: 10px;
      flex-shrink: 0;

      .item-price {
        font-size: 15px;
        color: #ff3366;
        font-weight: 600;
        margin-bottom: 12px;
      }

      .add-button {
        padding: 4px 14px;
        background-color: #fff;
        color: #ff3366;
        border: 1px solid #ff3366;
        border-radius: 15px;
        font-size: 12px;
        cursor: pointer;
        line-height: 1.5;
        height: auto;
        min-height: unset;

        &:active {
          background-color: rgba(255, 51, 102, 0.05);
        }

        &::after {
          border: none;
        }
      }
    }
  }
}

.image-placeholder {
  position: relative; // 添加相对定位
  transition: all 0.3s ease;
  
  &.animating {
    animation: imageFlash 1.2s ease; // 增加动画时间
  }
  
  &.generating {
    position: relative;
    overflow: hidden;
    
    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: -100%;
      width: 100%;
      height: 100%;
      background: linear-gradient(
        90deg, 
        rgba(255,255,255,0) 0%, 
        rgba(255,255,255,0.3) 50%, 
        rgba(255,255,255,0) 100%
      );
      animation: shine 1.5s infinite;
      z-index: 2;
    }
  }
  
  &.generated {
    animation: popEffect 0.8s ease; // 增强弹出效果
  }
  
  .model-image {
    opacity: 0.9;
  }
  
  .change-btn {
    position: absolute;
    right: 10px;
    bottom: 10px;
    background: linear-gradient(135deg, rgba(255,91,154,0.8) 0%, rgba(255,51,102,0.9) 100%);
    color: #fff;
    padding: 6px 16px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
    box-shadow: 0 2px 8px rgba(255, 51, 102, 0.3);
    transition: all 0.3s ease;
    z-index: 5;
    backdrop-filter: blur(2px);
    border: 1px solid rgba(255,255,255,0.2);
    
    &:active {
      transform: scale(0.95) translateY(1px);
      background: linear-gradient(135deg, rgba(255,91,154,0.9) 0%, rgba(255,51,102,1) 100%);
      box-shadow: 0 1px 4px rgba(255, 51, 102, 0.3);
    }
    
    &.top-z-index {
      z-index: 10; // 更高的z-index确保在生成图片和动画层之上
      background: rgba(255,51,102,0.9); // 更明显的背景以便于区分
      box-shadow: 0 2px 10px rgba(255, 51, 102, 0.5);
      border: 1px solid rgba(255,255,255,0.4);
    }
  }
  
  .generating-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255,255,255,0.7);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    z-index: 3;
    overflow: hidden; // 确保扫描线不超出容器
    
    .scanning-line {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 2px;
      background: linear-gradient(to right, 
        rgba(255,51,102,0) 0%, 
        rgba(255,51,102,0.8) 50%, 
        rgba(255,51,102,0) 100%
      );
      box-shadow: 0 0 8px rgba(255,51,102,0.5);
      animation: scanning 1.5s linear infinite;
      z-index: 4;
    }
    
    .generating-spinner {
      width: 40px;
      height: 40px;
      border: 3px solid rgba(255,51,102,0.3);
      border-top: 3px solid rgba(255,51,102,1);
      border-radius: 50%;
      margin-bottom: 15px;
      animation: spin 1s linear infinite;
    }
    
    .generating-text {
      color: #ff3366;
      font-size: 14px;
      font-weight: 500;
      margin-bottom: 12px;
    }
    
    .progress-container {
      width: 80%;
      height: 6px;
      background-color: rgba(255, 51, 102, 0.2);
      border-radius: 3px;
      overflow: hidden;
      
      .progress-bar {
        height: 100%;
        background: linear-gradient(to right, #ff3366, #ff5b9a);
        border-radius: 3px;
        transition: width 0.3s ease;
      }
    }
  }
  
  .success-animation {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 4;
    overflow: hidden; // 确保花瓣动画不超出容器
  }
}

// 动画定义
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes shine {
  0% { left: -100%; }
  100% { left: 100%; }
}

@keyframes scaleUp {
  0% { transform: scale(0); opacity: 0.8; }
  80% { transform: scale(1.1); opacity: 0.9; }
  100% { transform: scale(1); opacity: 1; }
}

@keyframes checkmark {
  0% { transform: rotate(45deg) scale(0); opacity: 0; }
  70% { transform: rotate(45deg) scale(1.2); opacity: 1; }
  100% { transform: rotate(45deg) scale(1); opacity: 1; }
}

@keyframes popEffect {
  0% { transform: scale(0.9); opacity: 0.5; }
  50% { transform: scale(1.15); opacity: 1; } // 增加缩放比例
  75% { transform: scale(0.95); opacity: 1; }
  100% { transform: scale(1); opacity: 1; }
}

@keyframes imageFlash {
  0% { transform: scale(1); filter: brightness(1); }
  40% { transform: scale(1.15); filter: brightness(1.2); } // 增加缩放比例
  60% { transform: scale(1.15); filter: brightness(1.2); } // 保持缩放状态更长时间
  100% { transform: scale(1); filter: brightness(1); }
}

// 添加新的闪光效果
@keyframes glow {
  0% { box-shadow: 0 0 5px rgba(255, 51, 102, 0.5); }
  50% { box-shadow: 0 0 20px rgba(255, 51, 102, 0.8); }
  100% { box-shadow: 0 0 5px rgba(255, 51, 102, 0.5); }
}

// 添加扩散效果
.success-animation {
  .success-ripple {
    position: absolute;
    border: 2px solid rgba(76, 175, 80, 0.5);
    border-radius: 50%;
    animation: ripple 1s ease-out forwards;
    opacity: 1;
  }
}

@keyframes ripple {
  0% { 
    width: 0; 
    height: 0; 
    opacity: 1; 
  }
  100% { 
    width: 200px; 
    height: 200px; 
    opacity: 0; 
    margin-left: -100px;
    margin-top: -100px;
  }
}

// 添加扫描动画
@keyframes scanning {
  0% { transform: translateY(0); opacity: 0.8; }
  50% { opacity: 1; }
  100% { transform: translateY(100vh); opacity: 0.8; }
}

// 添加模特动画样式
.model-area.animate-model {
  animation: modelEnterAnimation 1.2s ease-out forwards;
}

@keyframes modelEnterAnimation {
  0% {
    opacity: 0;
    transform: scale(0.8);
  }
  70% {
    opacity: 1;
    transform: scale(1.1);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

// 打字机文本样式
.luck-description {
  min-height: 1.5em; // 确保高度一致，避免打字时抖动
  overflow: visible;
  max-height: none;
  white-space: pre-line;
  word-break: break-word;
}

// 添加缩放后恢复的动画
@keyframes zoom-and-revert {
  0% { transform: scale(1); }
  40% { transform: scale(1.15); }
  80% { transform: scale(1.15); }
  100% { transform: scale(1); }
}

// 运势星级模块
.fortune-star-section {
  background-color: #fff;
  margin: 8px 0;
  padding: 14px 10px; // 增加垂直内边距
  border-radius: 0;
  box-shadow: none;
  border-top: 1px solid #f0f0f0;

  .fortune-star-header {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 6px;
  }
  .fortune-card-title {
    color: #a85ce0;
    font-size: 18px;
    font-weight: bold;
    letter-spacing: 1px;
    text-align: left;
    display: block;
  }
  .fortune-stars {
    display: flex;
    align-items: center;
    gap: 2px;
  }
  .fortune-star {
    font-size: 18px;
    color: #e0e0e0;
    margin-right: 2px;
  }
  .fortune-star.active {
    color: #ff5b9a;
    text-shadow: 0 1px 6px #ffd6e3;
  }
  .fortune-star-desc-row {
    display: flex;
    align-items: baseline;
    gap: 8px;
    margin-bottom: 0;
  }
  .fortune-star-score {
    font-size: 15px;
    font-weight: bold;
    color: #ff5b9a;
  }
  .fortune-summary {
    font-size: 15px;
    color: #888;
    font-weight: 400;
  }
}

// 个人幸运色模块
.lucky-color-section {
  background-color: #fff;
  margin: 8px 0;
  padding: 14px 10px; // 增加垂直内边距
  border-radius: 0;
  box-shadow: none;
  border-top: 1px solid #f0f0f0;

  .fortune-card-header {
    margin-bottom: 8px;
    .fortune-card-title {
      color: #ff5b9a;
      font-size: 18px;
      font-weight: bold;
      letter-spacing: 1px;
      text-align: left;
      display: block;
    }
  }
  .lucky-color-row {
    display: flex;
    align-items: center;
    gap: 36px;
    margin-bottom: 8px;
    margin-top: 4px;
  }
  .lucky-color-group {
    display: flex;
    align-items: center;
    gap: 6px;
  }
  .color-dot {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    border: 2px solid #fff;
    box-shadow: 0 2px 8px #e0eafc;
    &.main {
      background: linear-gradient(135deg,#e0eafc,#cfdef3);
    }
    &.assist {
      background: linear-gradient(135deg,#a8edea,#fed6e3);
    }
  }
  .color-label {
    color: #bbb;
    font-size: 15px;
    font-weight: bold;
  }
  .color-value {
    font-size: 16px;
    font-weight: bold;
    &.main { color: #4a90e2; }
    &.assist { color: #26a69a; }
  }
  .color-desc {
    color: #313131;
    font-size: 14px;
    margin-top: 2px;
    margin-left: 2px;
    display: block;
  }
}

// 2025年运势指数模块
.fortune-index-section {
  background-color: #fff;
  margin: 8px 0;
  padding: 14px 10px; // 增加垂直内边距
  border-radius: 0;
  box-shadow: none;
  border-top: 1px solid #f0f0f0;

  .fortune-index-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 18px;
    color: #333;
    letter-spacing: 0.5px;
  }

  .fortune-index-list {
    display: flex;
    flex-direction: column;
    gap: 18px;
    margin-top: 8px;
  }
  .fortune-index-item {
    display: flex;
    align-items: flex-start;
    gap: 16px;
    min-height: 38px;
  }
  .fortune-index-type {
    min-width: 48px;
    color: #a85ce0;
    font-weight: bold;
    font-size: 16px;
    text-align: right;
    line-height: 1.2;
    margin-top: 2px;
  }
  .fortune-index-stars {
    min-width: 90px;
    display: flex;
    align-items: center;
    margin-top: 2px;
  }
  .fortune-star {
    font-size: 18px;
    color: #e0e0e0;
    margin-right: 2px;
  }
  .fortune-star.active {
    color: #ff5b9a;
    text-shadow: 0 1px 6px #ffd6e3;
  }
  .fortune-index-desc {
    flex: 1;
    color: #666;
    font-size: 15px;
    line-height: 1.6;
    word-break: break-all;
  }
}

// 建议穿搭标签模块
.wear-tags-section {
  background-color: #fff;
  margin: 8px 0;
  padding: 14px 10px; // 增加垂直内边距
  border-radius: 0;
  box-shadow: none;
  border-top: 1px solid #f0f0f0;

  .fortune-card-header {
    margin-bottom: 8px;
    .fortune-card-title {
      color: #a85ce0;
      font-size: 18px;
      font-weight: bold;
      letter-spacing: 1px;
      text-align: left;
      display: block;
    }
  }
  .wear-tags-list {
    display: flex;
    flex-direction: column;
    gap: 18px;
  }
  .wear-tags-row {
    display: flex;
    align-items: flex-start;
    gap: 18px;
    margin-bottom: 0;
  }
  .tag-label {
    min-width: 70px;
    color: #a85ce0;
    font-weight: bold;
    font-size: 15px;
    text-align: right;
    margin-top: 2px;
    letter-spacing: 1px;
    white-space: nowrap;
    line-height: 1.8;
    display: flex;
    align-items: center;
  }
  .tags-group {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
  }
  .tag {
    display: inline-block;
    padding: 6px 18px;
    border-radius: 18px;
    font-size: 14px;
    font-weight: 500;
    box-shadow: 0 2px 8px rgba(168,92,224,0.08);
    background: #f5f5f5;
    color: #666;
    &.color.silver { background: linear-gradient(90deg,#e0eafc,#cfdef3); color:#888;}
    &.color.white { background: linear-gradient(90deg,#fff,#f5f5f5); color:#aaa;}
    &.color.green { background: linear-gradient(90deg,#a8edea,#b2f7cc); color:#4caf50;}
    &.color.blue { background: linear-gradient(90deg,#cfd9df,#e2ebf0); color:#4a90e2;}
    &.style.business { background: #e1f5fe; color: #26a69a;}
    &.style.retro { background: #e8f5e9; color: #8bc34a;}
    &.type.fabric { background: #fff3e0; color: #ff9800;}
    &.type.metal { background: #f3e5f5; color: #a1887f;}
  }
}

/* 卡片美化样式 */
.fortune-card {
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 6px 24px rgba(168,92,224,0.10);
  margin: 8px 0;
  padding: 22px 18px 18px 18px;
  position: relative;
  overflow: hidden;
  transition: box-shadow 0.3s;
  &:hover { box-shadow: 0 10px 32px rgba(168,92,224,0.16);}
}
.fortune-card-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  .fortune-card-title {
    font-size: 17px;
    font-weight: bold;
    background: linear-gradient(90deg,#ff5b9a,#a85ce0);
    background-clip: text;  
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    letter-spacing: 1px;
  }
}
.fortune-stars text,
.stars text {
  font-size: 20px;
  margin-right: 2px;
  color: #e0e0e0;
  &.active {
    background: linear-gradient(90deg,#ff5b9a,#a85ce0);
    background-clip: text;  
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    color: #ff5b9a;
    text-shadow: 0 2px 8px #ffd6e3;
  }
}
.fortune-star-score {
  font-size: 15px;
  color: #ff5b9a;
  font-weight: 600;
  margin-bottom: 6px;
}
.lucky-color-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  .color-dot {
    width: 18px; height: 18px; border-radius: 50%; margin-right: 6px; border:2px solid #fff;
    box-shadow: 0 2px 8px #e0eafc;
  }
  .color-label { color: #888; font-size: 13px; margin-right: 2px;}
  .color-value { color: #4a90e2; font-weight: 600; margin-right: 10px;}
}
.color-desc { color: #aaa; font-size: 12px; margin-top: 2px;}
.wear-tags-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
  .tag-label { min-width: 60px; color: #a85ce0; font-weight: 600; margin-top: 2px;}
  .tags-group { display: flex; flex-wrap: wrap; gap: 8px;}
  .tag {
    background: #f5f5f5;
    color: #666;
    border-radius: 12px;
    padding: 4px 14px;
    font-size: 12px;
    &.silver { background:linear-gradient(90deg,#e0eafc,#cfdef3); color:#888;}
    &.white { background:linear-gradient(90deg,#fff,#f5f5f5); color:#aaa;}
    &.green { background:linear-gradient(90deg,#a8edea,#fed6e3); color:#4caf50;}
    &.blue { background:linear-gradient(90deg,#cfd9df,#e2ebf0); color:#4a90e2;}
    &.style { background: #ffe6f0; color: #ff5b9a;}
    &.type { background: #e6ffe6; color: #4caf50;}
  }
}

.month-tips-section {
  background-color: #fff;
  margin: 8px 0;
  padding: 14px 10px;
  border-radius: 0;
  box-shadow: none;
  border-top: 1px solid #f0f0f0;
  .fortune-card-header {
    margin-bottom: 8px;
    .fortune-card-title {
      color: #a85ce0;
      font-size: 18px;
      font-weight: bold;
      letter-spacing: 1px;
      text-align: left;
      display: block;
    }
  }
  .month-tips-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
    margin-top: 4px;
  }
  .month-tip-item {
    display: flex;
    align-items: flex-start;
    font-size: 15px;
    color: #333;
    line-height: 1.8;
    background: #f8f6ff;
    border-radius: 10px;
    padding: 8px 12px;
    box-shadow: 0 2px 8px rgba(168,92,224,0.04);
    position: relative;
    .month-dot {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background: linear-gradient(135deg,#a85ce0,#ff5b9a);
      margin-right: 10px;
      margin-top: 7px;
      flex-shrink: 0;
    }
    .month-label {
      font-weight: bold;
      color: #a85ce0;
      min-width: 44px;
      display: inline-block;
      font-size: 15px;
      margin-right: 2px;
    }
    .month-tip-content {
      color: #444;
      font-size: 15px;
      margin-left: 2px;
      flex: 1;
      word-break: break-all;
    }
  }
}
</style> 